package com.edu.demo.service.impl;

import com.edu.demo.constant.CacheConstants;
import com.edu.demo.constant.UserConstant;
import com.edu.demo.entity.LoginUser;
import com.edu.demo.entity.Student;
import com.edu.demo.entity.SysUser;
import com.edu.demo.entity.Teacher;
import com.edu.demo.exception.CaptchaException;
import com.edu.demo.exception.MyNullPointerException;
import com.edu.demo.mapper.StudentMapper;
import com.edu.demo.mapper.SysUserMapper;
import com.edu.demo.mapper.TeacherMapper;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.IRoleService;
import com.edu.demo.utils.ServletUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: UserDetailServiceImpl
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-15
 */
@Service(value = "userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    private Map<String,String> loginRole;

    @Autowired
    private IRoleService roleService;

    private String loginType;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String loginType = this.loginType;
        LoginUser loginUser = null;
        loginRole = new HashMap<>();
        switch (loginType){
            case UserConstant.ADMIN_TYPE:
                SysUser user = sysUserMapper.selectByCode(username);
                if(Objects.isNull(user)) throw new UsernameNotFoundException("没有该学工号/学号的用户");
                 loginUser = LoginUser.builder().sysUser(user).status(user.getStatus()).type(UserConstant.ADMIN_TYPE).build();
                 loginUser.setPermissions(permissionService.getMenuPermission(user));
                break;
            case UserConstant.STUDENT_TYPE:
                Student stu = studentMapper.selectByCode(username);
                if(Objects.isNull(stu)) throw new UsernameNotFoundException("没有该学工号/学号的用户");
                loginUser = LoginUser.builder().student(stu).status(stu.getStatus()). type(UserConstant.STUDENT_TYPE).build();
                loginUser.setPermissions(permissionService.getMenuPermission(stu));
                break;
            case UserConstant.TEACHER_TYPE:
                Teacher teacher = teacherMapper.selectByCode(username);
                if(Objects.isNull(teacher)) throw new UsernameNotFoundException("没有该学工号/学号的用户");;
                loginUser = LoginUser.builder().teacher(teacher).status(teacher.getStatus()).type(UserConstant.TEACHER_TYPE).build();
                loginUser.setPermissions(permissionService.getMenuPermission(teacher));
                break;
        }

        if(loginUser == null) return null;
        return loginUser;
    }


    public AjaxResult login(String userName, String password, String code, String uuid ,String userType) throws CaptchaException {

        validateCode(code,uuid);
        if(Strings.isEmpty(userType)) throw new NullPointerException("错误：用户类型未传递!");
        this.loginType = userType;
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userName,password));
        AjaxResult result = AjaxResult.success();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = tokenService.createToken(loginUser);
        result.put("token",token);
        if(!Objects.isNull(loginRole)){
            result.put("role",loginRole.get("role"));
        }
        result.put("code",200);
        result.put("msg","登录成功");
        return result;
    }


    /**
     * 判断验证码是否合法
     * @param code
     * @param uuid
     * @throws CaptchaException
     */
    private void validateCode(String code,String uuid) throws CaptchaException {
        if(Strings.isEmpty(code)) throw new CaptchaException("验证码缺少");

        String key = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String code2 = (String) redisTemplate.opsForValue().get(key);
        redisTemplate.delete(key);
        if(Strings.isEmpty(code2)) throw new CaptchaException("验证码已过期");
        if(code.equals(code2)){}
        else throw new CaptchaException("验证码不正确");
    }





}
